<template>
  <el-dialog :visible.sync="visible"
             :title="!dataForm.id ? `${$t('add')}部门` : `${$t('update')}部门`"
             :close-on-click-modal="false"
             :append-to-body="true"
             :before-close="closeDialog"
             class="add-or-updata"
             width="35%"
             :close-on-press-escape="false">
    <el-form :model="dataForm"
             v-loading="dataListLoading"
             ref="dataForm"
             label-position="left"
             @keyup.enter.native="dataFormSubmitHandle()"
             label-width="120px">
      <el-form-item prop="name"
                    label="部门名称"
                    :rules="stringRule()">
        <el-input v-model.trim="dataForm.name"
                  maxlength="20"
                  show-word-limit
                  placeholder="部门名称"></el-input>
      </el-form-item>
      <el-form-item prop="code"
                    label="部门编号"
                    :rules="stringRule()">
        <el-input v-model.trim="dataForm.code"
                  maxlength="20"
                  show-word-limit
                  @input="val => dataForm.code = val.replace(/[^a-zA-Z0-9]/g, '')"
                  placeholder="部门编号"></el-input>
      </el-form-item>
      <el-form-item prop="parentName"
                    :rules="required()"
                    :label="$t('dept.parentName')"
                    class="dept-list">
        <el-popover v-model.trim="deptListVisible"
                    ref="deptListPopover"
                    placement="bottom-start"
                    trigger="click">
          <el-tree :data="deptList1"
                   :props="{ label: 'name', children: 'children' }"
                   node-key="id"
                   ref="deptListTree"
                   :highlight-current="true"
                   :expand-on-click-node="false"
                   accordion
                   @current-change="deptListTreeCurrentChangeHandle">
          </el-tree>
        </el-popover>
        <el-input v-model.trim="dataForm.parentName"
                  v-popover:deptListPopover
                  :readonly="true"
                  :disabled="isDisabled && dataForm.id"
                  :placeholder="$t('dept.parentName')">
        </el-input>
      </el-form-item>
      <el-form-item prop="prName"
                    label="选择负责人">
        <el-input v-model.trim="dataForm.prName"
                  class="width-100"
                  :readonly="true"
                  @focus="focusUser"
                  placeholder="选择负责人"></el-input>
      </el-form-item>
      <el-form-item prop="remarks"
                    label="备注">
        <el-input v-model.trim="dataForm.remarks"
                  type="textarea"
                  :autosize="{ minRows: 3, maxRows: 4}"
                  maxlength="50"
                  show-word-limit
                  placeholder="备注"></el-input>
      </el-form-item>
      <user-dialog ref="userDialog"
                   @callBack="userDialogCallBack" />
    </el-form>
    <template slot="footer">
      <el-button type="primary"
                 :loading="isRequest"
                 @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
      <el-button @click="closeDialog">{{ $t('cancel') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import mixinViewModule from '@/mixins/view-module'
import formValidate from '@/mixins/form-validate'
import debounce from 'lodash/debounce'
import userDialog from '@/components/user-dialog'
export default {
  mixins: [mixinViewModule, formValidate],
  data () {
    return {
      mixinViewModuleOptions: {
        getDataListURL: '',
        getDataInfoURL: '',
        addURL: '/system/sysDept', // 添加或修改的接口
        updateURL: '/system/sysDept' // 添加或修改的接口
      },
      visible: false,
      isRequest: false,
      deptList1: [],
      deptListVisible: false,
      isDisabled: false,
      dataForm: {
        id: '',
        name: '',
        pid: '',
        parentName: '',
        prName: '',
        code: '',
        remarks: '',
        userId: ''
      },
      afterId: ''
    }
  },
  components: {
    userDialog
  },
  computed: {
  },
  methods: {
    closeDialog () {
      this.dataForm.id = ''
      this.dataForm.name = ''
      this.dataForm.pid = ''
      this.dataForm.parentName = ''
      this.dataForm.prName = ''
      this.dataForm.code = ''
      this.dataForm.remarks = ''
      this.dataForm.userId = ''
      this.dataForm.afterId = ''
      this.deptList1 = []
      this.$refs['dataForm'].resetFields()
      this.visible = false
      this.$emit('callBack')
      this.isRequest = false
    },
    init (list, data) {
      this.visible = true
      // 添加部门列表

      if (list.length) {
        this.deptList1.splice(0, this.deptList1.length, ...list)
      }
      let obj = this.deptList1.find(item => item.id === '-2')
      if (!obj) {
        this.deptList1.unshift({
          id: '-2',
          name: '无'
        })
      }
      if (data) {
        this.dataForm = data
        this.afterId = this.dataForm.id
        if (this.dataForm.pid === '-2') {
          this.dataForm.parentName = '无'
        } else {
          let list = this.deptList1
          const selectMenu = list.filter(item => item.id === this.dataForm.pid)
          if (selectMenu.length) {
            this.dataForm.pid = selectMenu[0].id
            this.dataForm.parentName = selectMenu[0].name
          }
        }
      }
      this.$nextTick(() => {
      })
    },
    // 打开用户弹窗
    focusUser () {
      this.openDialog('userDialog')
    },
    // 用户弹窗回调
    userDialogCallBack (data) {
      this.dataForm = Object.assign({}, this.dataForm, {
        prName: data.realName,
        userId: data.id
      })
    },
    // 上级部门树, 选中
    deptListTreeCurrentChangeHandle (data) {
      if (this.afterId && data.id !== '0') {
        let deptItem = []
        let bool = false
        if (data.id === this.dataForm.id) {
          this.deptListVisible = false
          return this.$message.warning('禁止放置在自身以及其子菜单下面')
        }
        if (data.id === '-2') {
          this.dataForm.pid = data.id
          this.dataForm.parentName = data.name
          this.deptListVisible = false
        } else {
          deptItem = this.deptList1.filter(item => item.id === data.id)
          if (deptItem.length !== 0) {
            let selfItem = this.getDeptItem(this.dataForm.id, deptItem[0])
            if (selfItem) {
              bool = this.getDeptItem(data.id, selfItem)
            }
          }
          if (bool) {
            return this.$message.warning('禁止放置在自身以及其子菜单下面')
          }
          this.dataForm.pid = data.id
          this.dataForm.parentName = data.name
          this.deptListVisible = false
        }
      } else {
        this.dataForm.pid = data.id
        this.dataForm.parentName = data.name
        this.deptListVisible = false
      }
    },
    // 返回当前选中的部门本身以及所有的子级
    getDeptItem (id, deptItem) {
      let bool = false
      if (id === deptItem.id) {
        return deptItem
      }
      if (deptItem.children || deptItem.children.length) {
        deptItem.children.map(item => {
          if (bool) return bool
          bool = this.getDeptItem(id, item)
        })
      }
      return bool
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          this.isRequest = true
          const url = this.dataForm.id ? this.mixinViewModuleOptions.updateURL : this.mixinViewModuleOptions.addURL
          let arr = {}
          arr.name = this.dataForm.name
          arr.code = this.dataForm.code
          arr.pid = this.dataForm.pid
          arr.userId = this.dataForm.userId
          arr.remarks = this.dataForm.remarks
          if (this.dataForm.id) {
            arr.id = this.dataForm.id
            this.$http.put(url, arr).then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg)
              } else {
                this.$message.success('保存成功')
                this.closeDialog()
              }
            })
          } else {
            this.$http.post(url, arr).then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg)
              } else {
                this.$message.success('添加成功')
                this.closeDialog()
              }
            })
          }
        }
      })
    }, 1000, { 'leading': true, 'trailing': false })
  }
}
</script>

<style lang="scss">
.mod-sys__dept {
  .dept-list {
    .el-input__inner,
    .el-input__suffix {
      cursor: pointer;
    }
  }
}
</style>
